<template>
    <div class="container">
        <AtjHeader></AtjHeader>

        <div class="content-container">
            <!-- 标签筛选区 -->
            <div class="tags-filter">
                <h2>标签筛选</h2>
                <div class="tags-list">
                    <span 
                        v-for="tag in tags" 
                        :key="tag.id"
                        class="tag"
                        :class="{ active: currentTag === tag.id }"
                        @click="selectTag(tag.id)"
                    >
                        {{ tag.name }}
                        <span v-if="tag.id !== 'all'" class="tag-count">
                            ({{ tag.article_count }})
                        </span>
                    </span>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="content-wrapper" :class="{ 'is-loading': loading }" >
                <!-- 加载指示器 -->
                <div class="loading-overlay" v-show="loading">
                    <div class="loading-spinner"></div>
                </div>

                <!-- 错误提示 -->
                <div v-if="error" class="error">
                    {{ error }}
                </div>

                <!-- 无数据提示 -->
                <div v-else-if="articles.length === 0" class="no-data">
                    暂无相关文章
                </div>

                <!-- 文章列表 -->
                <transition-group 
                    name="article-list" 
                    tag="div" 
                    class="articles-grid"
                    v-else
                >
                    <div v-for="article in articles" 
                        :key="article.id" 
                        class="article-card"
                        @click="goToArticle(article.id)">
                        <div class="article-thumbnail">
                            <img :src="article.thumbnail_url" :alt="article.title">
                        </div>
                        <div class="article-info">
                            <h3>{{ article.title }}</h3>
                            <p>{{ article.description }}</p>
                            <div class="article-meta">
                                <span class="article-date">{{ formatDate(article.created_at) }}</span>
                                <span class="article-views">{{ article.view_count }} 阅读</span>
                            </div>
                        </div>
                    </div>
                </transition-group>
            </div>

            <!-- 分页 -->
           <div class="pagination" v-if="total > pageSize">
                <button 
                    class="pagination-btn prev"
                    :disabled="currentPage === 1"
                    @click="changePage(currentPage - 1)"
                >
                    <i class="arrow left"></i>
                    上一页
                </button>
                
                <div class="page-info">
                    <span class="current-page">{{ currentPage }}</span>
                    <span class="separator">/</span>
                    <span class="total-pages">{{ totalPages }}</span>
                </div>
                
                <button 
                    class="pagination-btn next"
                    :disabled="currentPage === totalPages"
                    @click="changePage(currentPage + 1)"
                >
                    下一页
                    <i class="arrow right"></i>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'  // 添加 watch
import { useRouter } from 'vue-router'
import { articleApi } from '@/api/article'
import { tagApi, type Tag } from '@/api/tag'
import AtjHeader from '@/components/AtjHeader.vue'
import { formatDate } from '@/utils/date'

interface ExtendedTag extends Tag {
    id: number | 'all';
}

const router = useRouter()

// 状态
const loading = ref(false)
const error = ref('')
const articles = ref([])
const tags = ref<ExtendedTag[]>([])
const currentTag = ref<number | 'all'>('all')  // 明确类型
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const totalPages = ref(0)

// 获取标签列表
const fetchTags = async () => {
    try {
        const response = await tagApi.getTags()
        
        if (Array.isArray(response)) {
            tags.value = [
                { 
                    id: 'all', 
                    name: '全部',
                    created_at: '',
                    article_count: 0
                }, 
                ...response
            ]
        } else {
            console.error('Invalid tags response format:', response)
            tags.value = [{ 
                id: 'all', 
                name: '全部',
                created_at: '',
                article_count: 0
            }]
        }
    } catch (err) {
        console.error('Error fetching tags:', err)
        tags.value = [{ 
            id: 'all', 
            name: '全部',
            created_at: '',
            article_count: 0
        }]
    }
}

// 获取文章列表
const fetchArticles = async () => {
    loading.value = true
    error.value = ''
    
    try {
        // 添加最小加载时间以避免闪烁
        const minLoadingTime = 300
        const startTime = Date.now()
        
        const params: any = {
            page: currentPage.value,
            pageSize: pageSize.value,
        }
        
        if (currentTag.value !== 'all') {
            params.tag_id = currentTag.value
        }

        const response = await articleApi.getArticles(params)
        
        // 确保最小加载时间
        const elapsedTime = Date.now() - startTime
        if (elapsedTime < minLoadingTime) {
            await new Promise(resolve => setTimeout(resolve, minLoadingTime - elapsedTime))
        }
        
        if (response && Array.isArray(response.data)) {
            articles.value = response.data
            total.value = response.total || response.data.length
            totalPages.value = Math.ceil(total.value / pageSize.value)
        } else if (Array.isArray(response)) {
            articles.value = response
            total.value = response.length
            totalPages.value = Math.ceil(total.value / pageSize.value)
        } else {
            throw new Error('Invalid articles response format')
        }
    } catch (err) {
        error.value = '获取文章列表失败，请稍后重试'
        console.error('Error fetching articles:', err)
        articles.value = []
    } finally {
        loading.value = false
    }
}


// 选择标签
const selectTag = (tagId: number | 'all') => {
    currentTag.value = tagId
    currentPage.value = 1  // 重置页码
    fetchArticles()
}
// 监听标签变化
watch(currentTag, () => {
    fetchArticles()
})
// 切换页面
const changePage = (page: number) => {
    currentPage.value = page
    fetchArticles()
}

// 跳转到文章详情
const goToArticle = (id:number) => {
  router.push({ path: '/article', query: { id: id } })
}

// 初始化
onMounted(() => {
    fetchTags()
    fetchArticles()
})
</script>
<style lang="less" scoped>
@import '@/assets/css/universal.css';
/* 内容容器 */
.content-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

/* 标签筛选区 */
.tags-filter {
    background-color: #fff;
    padding: 25px;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 30px;
}

.tags-filter h2 {
    color: #1a73e8;
    margin-bottom: 20px;
    font-size: 1.4em;
}

.tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.tag {
    padding: 8px 16px;
    background-color: #f0f7ff;
    color: #1a73e8;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.tag:hover {
    background-color: #1a73e8;
    color: #fff;
    transform: translateY(-2px);
}

.tag.active {
    background-color: #1a73e8;
    color: #fff;
}

/* 文章网格 */
.articles-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 25px;
    margin-bottom: 40px;
}

.article-card {
    background-color: #fff;
    border-radius: 15px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.article-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.article-thumbnail {
    width: 100%;
    height: 200px;
    overflow: hidden;
}

.article-thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.article-card:hover .article-thumbnail img {
    transform: scale(1.05);
}

.article-info {
    padding: 20px;
}

.article-info h3 {
    color: #2c3e50;
    font-size: 1.2em;
    margin-bottom: 10px;
    line-height: 1.4;
}

.article-info p {
    color: #666;
    font-size: 14px;
    margin-bottom: 15px;
    line-height: 1.6;
}

.article-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #888;
    font-size: 12px;
}

.article-tags {
    display: flex;
    gap: 8px;
}

.article-tag {
    padding: 4px 8px;
    background-color: #f0f7ff;
    color: #1a73e8;
    border-radius: 12px;
    font-size: 12px;
}

/* 精美的分页样式 */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 24px;
    margin: 40px auto;
    padding: 20px 0;
    max-width: 600px;

    /* 按钮基础样式 */
    .pagination-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 24px;
        background: linear-gradient(145deg, #ffffff, #f0f0f0);
        border: 1px solid #e0e0e0;
        border-radius: 25px;
        color: #1a73e8;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

        /* 箭头样式 */
        .arrow {
            width: 8px;
            height: 8px;
            border: solid #1a73e8;
            border-width: 0 2px 2px 0;
            display: inline-block;
            transition: all 0.3s ease;
            
            &.left {
                transform: rotate(135deg);
                margin-right: 4px;
            }
            
            &.right {
                transform: rotate(-45deg);
                margin-left: 4px;
            }
        }

        &:hover:not(:disabled) {
            background: linear-gradient(145deg, #1a73e8, #1557b0);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 115, 232, 0.2);

            .arrow {
                border-color: white;
            }
        }

        &:active:not(:disabled) {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(26, 115, 232, 0.1);
        }

        &:disabled {
            background: linear-gradient(145deg, #f5f5f5, #ebebeb);
            color: #bbb;
            border-color: #ddd;
            cursor: not-allowed;
            box-shadow: none;

            .arrow {
                border-color: #bbb;
            }
        }
    }

    /* 页码信息样式 */
    .page-info {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: #f8f9fa;
        border-radius: 16px;
        font-size: 14px;
        color: #444;
        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);

        .current-page {
            color: #1a73e8;
            font-weight: 600;
            font-size: 16px;
        }

        .separator {
            color: #999;
        }

        .total-pages {
            color: #666;
        }
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .pagination {
        gap: 16px;
        padding: 15px 0;

        .pagination-btn {
            padding: 8px 16px;
            font-size: 13px;

            .arrow {
                width: 6px;
                height: 6px;
            }
        }

        .page-info {
            padding: 6px 12px;
            font-size: 13px;

            .current-page {
                font-size: 14px;
            }
        }
    }
}

/* 添加深色模式支持 */
@media (prefers-color-scheme: dark) {
    .pagination {
        .pagination-btn {
            background: linear-gradient(145deg, #2c2c2c, #242424);
            border-color: #333;
            color: #89b4f4;

            &:hover:not(:disabled) {
                background: linear-gradient(145deg, #1a73e8, #1557b0);
                color: white;
            }

            &:disabled {
                background: linear-gradient(145deg, #2a2a2a, #222);
                color: #666;
                border-color: #333;
            }
        }

        .page-info {
            background: #2c2c2c;
            color: #ccc;

            .current-page {
                color: #89b4f4;
            }

            .separator {
                color: #666;
            }

            .total-pages {
                color: #999;
            }
        }
    }
}

/* 添加动画效果 */
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

.pagination-btn:not(:disabled):active {
    animation: pulse 0.3s ease-in-out;
}

.page-numbers {
    display: flex;
    gap: 10px;
}

.page-number {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s ease;
}

.page-number:hover,
.page-number.active {
    background-color: #1a73e8;
    color: #fff;
}

.prev-page,
.next-page {
    padding: 8px 20px;
    background-color: #f0f7ff;
    color: #1a73e8;
    border: none;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.prev-page:hover,
.next-page:hover {
    background-color: #1a73e8;
    color: #fff;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .content-container {
        padding: 15px;
    }

    .articles-grid {
        grid-template-columns: 1fr;
    }

    .article-thumbnail {
        height: 180px;
    }


}
// 内容包装器
.content-wrapper {
    position: relative;
    min-height: 200px;
    transition: opacity 0.3s ease;

    &.is-loading {
        opacity: 0.6;
        pointer-events: none;
    }
}

// 加载遮罩层
.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
}

// 加载动画
.loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #1a73e8;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

// 文章列表过渡动画
.article-list-enter-active,
.article-list-leave-active {
    transition: all 0.5s ease;
}

.article-list-enter-from {
    opacity: 0;
    transform: translateY(30px);
}

.article-list-leave-to {
    opacity: 0;
    transform: translateY(-30px);
}

// 确保文章卡片在动画过程中保持其网格位置
.articles-grid {
    position: relative;
    min-height: 200px;
}

.article-card {
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
    }
}

// 优化错误和无数据状态的显示
.error,
.no-data {
    text-align: center;
    padding: 40px;
    margin: 20px 0;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.error {
    color: #ff4d4f;
    border-left: 4px solid #ff4d4f;
}

.no-data {
    color: #666;
    border-left: 4px solid #1a73e8;
}
</style>